package com.mentalhealthplatform.studentV3.controller;

import com.mentalhealthplatform.global.rbac.model.CustomUserDetails;
import com.mentalhealthplatform.studentV3.dto.AssessmentDTOV3;
import com.mentalhealthplatform.studentV3.dto.FilterParamsV3;
import com.mentalhealthplatform.studentV3.service.AssessmentServiceV3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * @author Pear
 */
@RestController
@RequestMapping("/api/v3/assessments")
public class AssessmentControllerV3 {
    private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(AssessmentControllerV3.class);

    @Autowired
    private AssessmentServiceV3 assessmentServiceV3;

    @PostMapping
    public List<AssessmentDTOV3> getAssessments(@RequestBody FilterParamsV3 filterParamsV3) {
        return assessmentServiceV3.getFilteredAssessments(filterParamsV3);
    }


    @GetMapping("/current-username")
    public String getCurrentUsername() {
        // 获取当前用户的身份信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            // 返回当前用户的用户名
            return authentication.getName();
        }
        // 如果未获取到用户，返回 null
        return null;
    }


    @PostMapping("/submit")
    public ResponseEntity<String> submitAssessmentResults(@RequestBody AssessmentDTOV3 result) {
        // 打印提交的评估结果
        System.out.println("提交的评估结果: " + result);

        // 获取当前用户的用户名
        String currentUsername = getCurrentUsername();
        if (currentUsername == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户未登录");
        }
        result.setSubmittedTime(LocalDateTime.now());
        try {
            // 这里可以调用服务来处理评估结果的存储
            assessmentServiceV3.saveAssessmentResult(result, currentUsername);
            return ResponseEntity.ok("提交成功");
        } catch (Exception e) {
            // 处理保存过程中可能出现的异常
            System.err.println("保存评估结果时出错: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("提交失败: " + e.getMessage());
        }
    }

    // 获取当前用户ID
    @GetMapping("/current-id")
    public ResponseEntity<UUID> getCurrentStudentId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof CustomUserDetails userDetails) {
            return ResponseEntity.ok(userDetails.getId());
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
    }

    // 获取历史测评信息
    @GetMapping("/history")
    public ResponseEntity<List<AssessmentDTOV3>> getHistoryAssessments(@RequestParam UUID studentId) {
        List<AssessmentDTOV3> assessments = assessmentServiceV3.getHistoryAssessmentsByStudentId(studentId);
        return ResponseEntity.ok(assessments);
    }

    // 如果 content 为空，将会抛出 MethodArgumentNotValidException
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        return ResponseEntity.badRequest().body(ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }


}




